<?php
namespace app\admin\controller;

use app\admin\controller\Admin;
use think\Request;
use think\Db;
use app\common\model\AuthGroup;
use app\common\model\AuthRule;
use app\common\model\AuthAccess;

class Group extends Admin
{

    public function index()
    {
        $data = AuthGroup::getList();
        $this->assign('data',$data);
        return $this->fetch('admin/group/index');
    }

    public function create()
    {
        $data['ruleList'] = AuthRule::getListTree();
        $this->assign('data',$data);
        return $this->fetch('admin/group/create');
    }

    public function store()
    {
        $data = Request::instance()->param();
        $group_id = AuthGroup::store($data);
        empty($data['rules']) ? $data['rules'] = array() : $data['rules'];
        if ($group_id) {
            $access = AuthAccess::store($group_id, $data['rules']);
        }
        if ($group_id !== false && $access !== false) {
            return $this->response(200);
        } else {
            return $this->response(201);
        }
    }

    public function edit()
    {
        $map['id'] = Request::instance()->param('id');
        //获取组信息
        $data = AuthGroup::getInfo($map['id']);
        //获取所有权限列表
        $data['ruleList'] = AuthRule::getListTree();
        //获取当前组拥有的权限集合
        $data['access'] =  AuthAccess::getAccess($map['id']);
        // print_r($data);die;
        $this->assign('data',$data);
        return $this->fetch('admin/group/edit');
    }

    public function update()
    {
        $data = Request::instance()->param();
        empty($data['rules']) ? $data['rules'] = array() : $data['rules'];
        $group = AuthGroup::updateData($data);
        $access = AuthAccess::store($data['id'], $data['rules']);
        // var_dump($group);die;
        if ($group !== false && $access !== false) {
            return $this->response(200);
        } else {
            return $this->response(201);
        }
    }

    public function remove()
    {
        $id = Request::instance()->param('id');
        Db::startTrans();
        $group = AuthGroup::remove($id);
        $access = AuthAccess::remove($id);
        if ($group !== false && $access !== false) {
            Db::commit();
            return $this->response(200);
        } else {
            Db::rollback();
            return $this->response(201);
        }
    }

}
